package repo

import (
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model"
	"gorm.io/gorm"
	"sync"
)

type PostRepository struct {
}

var postRepositoryInstance *PostRepository
var oncePostRepository sync.Once

func GetPostRepository() *PostRepository {
	oncePostRepository.Do(func() {
		postRepositoryInstance = new(PostRepository)
	})
	return postRepositoryInstance
}

func (receiver PostRepository) FindStatisticsByPostIDs(postIDs []uint64) (list []model.PostStatistics, err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		tmpList := make([]model.PostStatistics, 0)
		err = db.Model(&model.PostStatistics{}).
			Where("post_id IN (?)", postIDs).
			Find(&tmpList).
			Error
		if err != nil {
			return
		}
		list = tmpList
	})
	return
}

func (receiver PostRepository) AddStatisticsView(postID uint64, addCount int) (err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		err = db.Model(&model.PostStatistics{}).
			Where("post_id = ?", postID).
			UpdateColumn("view_count", gorm.Expr("view_count + ?", addCount)).
			Error
	})
	return
}
